const app = getApp()
// 将 OpenAI API Key 替换为自己的
Page({
  data: {
    messages: [],
    inputMessage: '',
    toView: '',
    isTyping: false,
    loading:true,
  },

  onLoad: function () {
    wx.setNavigationBarTitle({
      title: 'ChatGPT 小程序'
    })
  },

  onInput: function (event) {
    this.setData({
      inputMessage: event.detail.value
    })
  },

  onSend: function () {
    const { messages, inputMessage, isTyping } = this.data

    if (inputMessage === '') {
      return
    }
    messages.push({
      role: 'user',
      content: inputMessage
    })

    this.setData({
      messages,
      inputMessage: '',
      toView: `msg-${messages.length - 1}`,
      isTyping: true
    })

    this.requestChat(inputMessage)
  },

  requestChat:async function (message) {
    const { messages } = this.data
    messages.push({
      role: 'other',
      content: '',
      wating:true
    })
    this.setData({
      messages,
      toView: `msg-${messages.length - 1}`,
      isTyping: false
    })
    const data=this.data.messages.filter(item=>item.role=='user')
    const parm=JSON.stringify(data);
    
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      headers: {
        'Authorization': `Bearer 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`,
        'Content-Type': 'application/json'
      },
      data:{
        messages:JSON.parse(parm),
        model: 'gpt-3.5-turbo',
        max_tokens: 1200,
        frequency_penalty: 0,
        presence_penalty:0.6,
        stream: false,
        temperature:0.5,
        top_p:1,
      },
      success: res => {
        if(res.result=='对不起，出错了')
        {
          messages[messages.length - 1]={
            role: 'role',
            content: res.result
          };
        }else
        {
          const role=res.result.message.role.trim();
          const backmsg = res.result.message.content.trim();
          messages[messages.length - 1]={
            role: role,
            content: backmsg
          };
        }
       
       // messages[messages.length - 1]=({)

        this.setData({
          messages,
          toView: `msg-${messages.length - 1}`,
          isTyping: false
        })
      },
      fail: err => {
        console.error(err)
      }
    })
  }
})
